package com.foreknow.controller;

import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Guestbook;
import com.foreknow.service.impl.GuestbookServiceImpl;
import com.foreknow.util.Pagination;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ManagerServlet extends HttpServlet {
    private int pageSize =10;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String contextPath = req.getContextPath();
        req.setAttribute("contextPath",contextPath);
        //获取请求参数q
        String method = req.getParameter("q");
        if("delete".equals(method)){
            delete(req,resp);
        }else if("update".equals(method)){
            update(req,resp);
        }else if ("queryById".equals(method)){
            queryById(req,resp);
        } else{
            list(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取初始化参数pageSize
        this.pageSize = Integer.parseInt(config.getServletContext().getInitParameter("pageSize"));
    }

    //查询所以留言信息
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        GuestbookServiceImpl guestbookService = new GuestbookServiceImpl();
        int pageNumber = 0;
        //获取请求的参数（pageNo页码）
        try{
            //当第一次进入到list.jsp时，页面是获取不到的，如果获取不到页码就执行catch，将页码置为1
            pageNumber = Integer.parseInt(req.getParameter("pageNo"));//list.jsp 传过来的pageNo
        }catch (Exception e){
            pageNumber=1;
        }
        Pagination pagination = guestbookService.getByPage(pageSize,pageNumber);
        MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = pagination.getList(mapping);
        //将list集合在服务器端保存（后期就可以在页面中获取到list集合）
        HttpSession session = req.getSession();
        session.setAttribute("list",list);
        session.setAttribute("total",pagination.getMaxElements());
        session.setAttribute("pageNo",pagination.getPageNumber());
        // 将资源转发到list.jsp
//        req.getRequestDispatcher("/list.jsp").forward(req,resp);
        resp.sendRedirect(req.getContextPath()+"/list.jsp");
    }



    //根据id删除留言信息
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        GuestbookServiceImpl guestbookService = new GuestbookServiceImpl();
        int id = Integer.parseInt(req.getParameter("id"));
//        Integer id = Integer.valueOf(req.getParameter("id"));
        boolean b = guestbookService.deleteById(id);
        if (b){
            list(req,resp);
        }else {
            out.println("删除失败");
        }
    }
    //查询id
    protected void queryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        GuestbookServiceImpl guestbookService = new GuestbookServiceImpl();
        int i = Integer.parseInt(req.getParameter("id"));
        Guestbook queryById = guestbookService.getQueryById(i);
        //将list集合在服务器端保存（后期就可以在页面中获取到list集合）
        req.setAttribute("guestBook",queryById);
        // 将资源转发到list.jsp
        req.getRequestDispatcher("/QueryById.jsp").forward(req,resp);
    }

    //修改留言信息
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        GuestbookServiceImpl guestbookService = new GuestbookServiceImpl();
        Integer id = Integer.valueOf(req.getParameter("id"));
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);

        Guestbook guestbook = new Guestbook();
        guestbook.setName(name);
        guestbook.setPhone(phone);
        guestbook.setEmail(email);
        guestbook.setTitle(title);
        guestbook.setContent(content);
        guestbook.setCreatedTime(format);
        int isRight = guestbookService.Update(guestbook, id);
        if (isRight==1){
            list(req,resp);
        }else {
            out.println("修改失败");
        }
    }
}
